<?php
#+------------------------------------------------------------------
#| 我曾七次鄙视自己的灵魂:
#| 第一次,当它本可进取时，却故作谦卑；
#| 第二次,当它空虚时，用爱欲来填充；
#| 第三次,在困难和容易之间，它选择了容易；
#| 第四次,它犯了错，却借由别人也会犯错来宽慰自己；
#| 第五次,它自由软弱，却把它认为是生命的坚韧；
#| 第六次,当它鄙夷一张丑恶的嘴脸时，却不知那正是自己面具中的一副；
#| 第七次,它侧身于生活的污泥中虽不甘心，却又畏首畏尾。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\common\lib\queue;

use app\common\lib\Identity;
use app\common\lib\Ip;
use app\common\model\ShortUrlLog;
use app\common\model\User;
use app\common\model\VisitLog;
use think\facade\Db;
use think\facade\Log;
use think\queue\Job;

class VisitShortUrl
{
    public function fire(Job $job, $params)
    {
        $short = $params['short'];
        $ip = $params['ip'];
        $device = $params['device'];
        $referer = $params['referer'] ?? '';
        Log::write(json_encode($params));
        $shortUrlLog = ShortUrlLog::withTrashed()->where('short_code', $short)->findOrEmpty();
        if ($shortUrlLog->isEmpty()) {
            $job->delete();
            return;
        }

        Db::startTrans();
        try {
            $shortUrlLog->visit += 1;
            $shortUrlLog->save();
            $ipManage = new Ip($ip);
            $create = [
                'ip'       => $ip,
                'city'     => $ipManage->city(),
                'province' => $ipManage->province(),
                'device'   => $device,
                'lat'      => $ipManage->lat(),
                'lon'      => $ipManage->lon(),
                'short'    => $short,
                'url_id'   => $shortUrlLog->id,
                'referer'  => $referer,
            ];
            /* Log::write('[保存访问数据失败]'.$exception->getMessage());
             $create = [
                 'ip'       => $ip,
                 'city'     => '',
                 'province' => '',
                 'device'   => $device,
                 'lat'      => '',
                 'lon'      => '',
                 'short'    => $short,
                 'url_id'   => $shortUrlLog->id,
                 'referer'  => $referer,
             ];*/
            echo json_encode($create).PHP_EOL;
            VisitLog::create($create);

            $config = config('system.' . $shortUrlLog->scene);

            if ($config['visit'] > 0) {
                $user = User::find($shortUrlLog->user_id);
                $user->money = bcsub($user->money - $config['visit']);
                $user->save();
            }
            Db::commit();
            $job->delete();
        } catch (\Exception $exception) {
            echo $exception->getMessage().PHP_EOL;
            echo $exception->getFile().':'.$exception->getLine().PHP_EOL;
            Db::rollback();
        }
    }
}